package com.ly.mp.busicen.rule.field.validator.plugin;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.ly.mp.busicen.rule.field.validator.IValidData;
import com.ly.mp.busicen.rule.field.validator.IValidation;
import com.ly.mp.busicen.rule.field.validator.ValidMsg;
import com.ly.mp.busicen.rule.field.validator.ValidatorBase;

/**
 * 字符串长度校验
 * 
 * @author ly-liuweisong
 *
 */
@Component
public class FieldLengthValid extends ValidatorBase {

	@Override
	public boolean valid(IValidData validData, IValidation validation) {
		Object value= validData.value();
		if (!StringUtils.isEmpty(value)) {
		    // <length>(0,36)[]; ,拆小括号, 0,30
			String param = validation.strParam();
			if (!StringUtils.isEmpty(param)) {
				String[] mm = param.split(",");
				if (mm.length == 2) {
					int len = String.valueOf(value).length();
					return len >= min(mm[0]) && len <= max(mm[1]);
				}
			}
		}
		return true;
	}

	private int min(String min) {
		if (StringUtils.isEmpty(min)) {
			return 0;
		}
		return Integer.parseInt(min);
	}

	private int max(String max) {
		if (StringUtils.isEmpty(max)) {
			return Integer.MAX_VALUE;
		}
		return Integer.parseInt(max);
	}

	@Override
	public String validName() {
		return "length";
	}
	
	@Override
	public ValidMsg errorMsg(IValidation validation) {		
		ValidMsg validMsg = super.errorMsg(validation);
		String[] params = validation.strParam().split(",");
		validMsg.setParams(params);		
		return validMsg;
	}

}
